package com.wk.springboot.lambda;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.wk.springboot.mapper.IUserDao;
import com.wk.springboot.mapper.User;
import org.junit.jupiter.params.shadow.com.univocity.parsers.common.DataValidationException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class UserService {

    @Autowired
    IUserDao userDao;

    public void queryUSer(String userId){
        checkUserExistence(userId);
        checkDeptExistence();
    }





    // 判断用户 ID 是否有效
    public void checkUserExistence(String userId) {
        User user = userDao.queryUserInfoById(Long.valueOf(userId));
        if (user == null) {
            throw new RuntimeException("用户ID无效");
        }
    }

    // 判断部门 ID 是否有效
    public void checkDeptExistence() {
        List<User> users = userDao.queryUserInfoList();
        if (users == null) {
            throw new RuntimeException("用户为空");
        }
    }



    /**
     * 确认数据库字段值有效（通用）
     *
     * @param <V> 待验证值的类型
     * @param valueToCheck 待验证的值
     * @param columnExtractor 实体类属性提取函数
     * @param queryExecutor 单条数据查询执行器
     * @param errorMessage 异常提示信息模板
     */
    public static <T, R, V> void ensureColumnValueValid(V valueToCheck, SFunction<T, R> columnExtractor,
                                                        SFunction<LambdaQueryWrapper<T>, T> queryExecutor,
                                                        String errorMessage) {
        if (valueToCheck == null) return;

        LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(columnExtractor);
        wrapper.eq(columnExtractor, valueToCheck);
        wrapper.last("LIMIT 1");

        T entity = queryExecutor.apply(wrapper);
        R columnValue = columnExtractor.apply(entity);
        if (entity == null || columnValue == null)
            throw new DataValidationException(String.format(errorMessage, valueToCheck));
    }
}
